<template>
  <div class="ds-container">
    <div class="ds-container-left lnsDataPanelWrapper ">
      <div class="filter-bar lnsInnerIndexPatternDataPanel">
        <div class="query-input">
          <el-input
            prefix-icon="el-icon-search"
            placeholder="Type something"
            size="default"
            v-model="queryFieldInput"
            @input="filterChange"
          >
          </el-input>
        </div>
        <vuedraggable
          class="wrapper"
          v-model="allFields"
          :options="{ group: { name: 'itxst', pull: 'clone' }, sort: false }"
          @end="dragEnd"
          chosenClass="chosen"
          animation="300"
          filter=".forbid"
        >
          <transition-group>
            <div
              :class="item.class"
              class="kbnFieldButton lnsFieldItem lnsFieldItem--date lnsFieldItem--exists lnsDragDrop lnsDragDrop-isDraggable"
              v-for="item in allFields"
              :key="item.id"
            >
              <p>{{ item.fieldEnName }} - {{ item.fieldZhName }}</p>
            </div>
          </transition-group>
        </vuedraggable>
      </div>
    </div>
    <vuedraggable v-model="selectedFields" group="itxst" ghostClass="ghost">
      <div class="ds-container-mid">
        <div
          v-if="selectedFields.length > 0"
          id="dsChart"
          style="width: 70%;height: 80%;position: fixed;"
        ></div>
        <div v-if="selectedFields.length == 0">
          <div class="euiTextAlign euiTextAlign--center">
            <div class="euiTextColor euiTextColor--subdued"></div>
          </div>
        </div>
      </div>
    </vuedraggable>
    <div class="ds-container-right">
      <div>
        <el-button
          type="success"
          @click="dialogSaveVisible = true"
          style="width: 100%;"
          >保存</el-button
        >
      </div>
      <div class="euiFormRow euiFormRow--fullWidth lnsLayerPanel__row">
        <div class="euiFormRow__labelWrapper">
          <legend class="euiFormLabel euiFormRow__label" aria-invalid="false">
            Y轴
          </legend>
        </div>
        <div class="euiFormRow__fieldWrapper">
          <div
            class="lnsLayerPanel__dimensionContainer"
            data-test-subj="lnsXY_xDimensionPanel"
          >
            <div
              data-test-subj="lnsDragDropContainer"
              class="lnsDragDrop__container"
            >
              <div
                class="lnsDragDrop lnsDragDrop-isDroppable lnsLayerPanel__dimension lnsLayerPanel__dimension--empty"
                data-test-subj="lnsDragDrop"
              >
                <button
                  class="euiButtonEmpty euiButtonEmpty--text euiButtonEmpty--small lnsLayerPanel__triggerText"
                  type="button"
                  aria-label="记录计数"
                  @click="onSelectYColumn()"
                  v-if="yColumn && yColumn.id > 0"
                >
                  <span
                    class="euiButtonContent euiButtonEmpty__content lnsLayerPanel__triggerTextContent"
                  >
                    <i class="el-icon-edit"></i>
                    <span class="euiButtonEmpty__text">
                      {{ yColumn.fieldEnName }} -
                      {{ yColumn.fieldZhName }}</span
                    ></span
                  >
                </button>

                <button
                  class="euiButtonEmpty euiButtonEmpty--text euiButtonEmpty--small lnsLayerPanel__triggerText"
                  type="button"
                  aria-label="记录计数"
                  @click="onSelectYColumn()"
                  v-if="yColumn && yColumn.id == ''"
                >
                  <span
                    class="euiButtonContent euiButtonEmpty__content lnsLayerPanel__triggerTextContent"
                  >
                    <i class="el-icon-edit"></i>
                    <span class="euiButtonEmpty__text">记录计数</span></span
                  >
                </button>

                <button
                  class="euiButtonEmpty euiButtonEmpty--text euiButtonEmpty--small lnsLayerPanel__triggerText"
                  type="button"
                  aria-label="添加字段"
                  @click="onSelectYColumn()"
                  v-if="!yColumn && xColumns.length == 0"
                >
                  <span
                    class="euiButtonContent euiButtonEmpty__content lnsLayerPanel__triggerTextContent"
                  >
                    <i class="el-icon-circle-plus"></i>
                    <span class="euiButtonEmpty__text">添加字段</span></span
                  >
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="euiFormRow__labelWrapper">
          <legend class="euiFormLabel euiFormRow__label" aria-invalid="false">
            X轴
          </legend>
        </div>
        <div class="euiFormRow__fieldWrapper">
          <div
            class="lnsLayerPanel__dimensionContainer"
            data-test-subj="lnsXY_xDimensionPanel"
          >
            <div
              class="lnsLayerPanel__dimensionContainer"
              v-for="item in xColumns"
              :key="item.id"
            >
              <div class="lnsDragDrop__container">
                <div
                  class="lnsDragDrop lnsDragDrop-isDroppable lnsLayerPanel__dimension lnsLayerPanel__dimension--empty background-fff"
                >
                  <button
                    class="euiLink euiLink--primary lnsLayerPanel__dimensionLink"
                    type="button"
                    @click="onSelectXColumn(item)"
                  >
                    {{ item.fieldEnName }} - {{ item.fieldZhName }}</button
                  ><button
                    class="euiLink euiLink--delte"
                    type="button"
                    @click="onUnSelectXColumn(item)"
                  >
                    <i class="el-icon-close"></i>
                  </button>
                </div>
              </div>
            </div>
            <div
              data-test-subj="lnsDragDropContainer"
              class="lnsDragDrop__container"
            >
              <div
                class="lnsDragDrop lnsDragDrop-isDroppable lnsLayerPanel__dimension lnsLayerPanel__dimension--empty"
                data-test-subj="lnsDragDrop"
              >
                <button
                  class="euiButtonEmpty euiButtonEmpty--text euiButtonEmpty--small lnsLayerPanel__triggerText"
                  type="button"
                  aria-label="添加字段"
                  @click="onSelectXColumn(undefined)"
                >
                  <span
                    class="euiButtonContent euiButtonEmpty__content lnsLayerPanel__triggerTextContent"
                  >
                    <i class="el-icon-circle-plus"></i>
                    <span class="euiButtonEmpty__text">添加字段</span></span
                  >
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="popupData" label-width="100px">
        <div v-if="popupData.columnType == 'y'">
          <el-form-item label="Y轴参数">
            <el-select
              v-model="popupData.selectedField"
              filterable
              @change="onSelectYField()"
              placeholder="请选择"
            >
              <el-option-group
                v-for="group in fieldOptions"
                :key="group.label"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <div v-if="popupData.fieldType == 'Date'">
            <el-form-item label="分组时间单位">
              <el-radio-group v-model="popupData.selUnit">
                <el-radio-button label="日"></el-radio-button>
                <el-radio-button label="周"></el-radio-button>
                <el-radio-button label="月"></el-radio-button>
                <el-radio-button label="年"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-if="popupData.fieldType == 'Num'">
            <el-form-item label="分组数字间隔">
              <el-input
                type="number"
                v-model="popupData.interval"
                placeholder="请输入数字间隔"
                style="width: 215px;"
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div v-if="popupData.columnType == 'x'">
          <el-form-item label="X轴参数">
            <el-select
              v-model="popupData.selectedField"
              filterable
              @change="onSelectXField()"
              placeholder="请选择"
            >
              <el-option-group>
                <el-option
                  v-for="item in fieldOptions[1].options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="
                    xColumns.filter(m => m.id == item.value).length > 0
                  "
                >
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <div v-if="popupData.selFun">
            <el-form-item label="聚合函数" v-if="popupData.fieldType == 'Num'">
              <el-radio-group v-model="popupData.selFun">
                <el-radio-button label="count"></el-radio-button>
                <el-radio-button label="sum"></el-radio-button>
                <el-radio-button label="max"></el-radio-button>
                <el-radio-button label="avg"></el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="聚合函数" v-if="popupData.fieldType == 'Date'">
              <el-radio-group v-model="popupData.selFun">
                <el-radio-button label="日"></el-radio-button>
                <el-radio-button label="周"></el-radio-button>
                <el-radio-button label="月"></el-radio-button>
                <el-radio-button label="年"></el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="聚合函数"
              v-if="
                popupData.fieldType != 'Num' && popupData.fieldType != 'Date'
              "
            >
              <el-radio-group v-model="popupData.selFun">
                <el-radio-button label="count"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <p v-if="dialogMsg" style="color:red;">{{ dialogMsg }}</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSave()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogSaveVisible"
      width="30%"
      :show-close="false"
    >
      <span>确定保存？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSaveVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import vuedraggable from 'vuedraggable';
import ChartData from '@/utils/chart';
import FilterBar from './components/filterBar.vue';
import Vue from 'vue';
export default {
  name: 'dualStackChart',
  components: {
    vuedraggable,
    FilterBar,
  },
  props: {},
  data() {
    return {
      myChart: undefined,
      fieldTypes: [
        { type: 'Num', text: '数字' },
        { type: 'String', text: '字符串' },
        { type: 'Date', text: '时间' },
        { type: '', text: '其它' },
      ],
      allFields: [],
      fieldOptions: [],
      selectedFields: [],
      popupData: {
        id: Number,
        fieldType: String,
        selFun: String,
        columnType: String,
      },
      xColumns: [],
      yColumn: undefined,
      dialogTitle: '',
      dialogMsg: '',
      dialogVisible: false,
      dialogSaveVisible: false,
      queryFieldInput: '',
    };
  },
  computed: {},
  created() {
    this.$store
      .dispatch('getOptionalField_action')
      .then(res => {
        if (res.statusCode === 200) {
          this.allFields = res.data;
          this.fieldOptions.push({
            label: '#',
            options: [
              {
                value: '',
                label: '记录',
              },
            ],
          });

          let options = [];
          this.allFields.forEach(item => {
            item.class = 'item';
            options.push({
              value: item.id,
              label: item.fieldEnName + '-' + item.fieldZhName,
            });
          });

          this.fieldOptions.push({
            label: '可用字段',
            options: options,
          });
        }
      })
      .catch(err => {
        console.error(err);
      });
  },
  updated() {},
  mounted() {},
  methods: {
    dragEnd() {
      if (this.selectedFields.length > 0) {
        this.onMove();
        this.$forceUpdate();
      }
    },
    onMove() {
      this.selectedFields.forEach(item => {
        var columns = this.xColumns.filter(m => m.id == item.id);
        if (columns.length == 0) {
          let column = {
            id: item.id,
            column: item.fieldEnName,
            fieldZhName: item.fieldZhName,
            fieldEnName: item.fieldEnName,
            fieldType: item.fieldType,
            function: 'count',
          };

          if (item.fieldType && item.fieldType == 'Date') {
            column.function = '日';
          }
          this.xColumns.push(column);

          if (!this.yColumn) {
            this.yColumn = { id: '' };
          }
        }
      });

      this.refreshChart();

      this.allFields.forEach(item => {
        var e = this.selectedFields.filter(m => m.id == item.id);
        if (e && e.length > 0) {
          item.class = 'item forbid';
        }
      });
    },
    handleClose(done) {
      //this.$confirm('确认关闭？')
      //  .then(_ => {
      //    done();
      //  })
      //  .catch(_ => { });
      this.dialogMsg = '';
      done();
    },
    save() {
      this.dialogSaveVisible = false;
      this.$message({
        message: '恭喜你，保存成功',
        type: 'success',
      });
    },
    onSelectXColumn(item) {
      this.popupData.id = 0;
      Vue.set(this.popupData, 'columnType', 'x');
      Vue.set(this.popupData, 'selectedField', '');
      Vue.set(this.popupData, 'selFun', '');

      if (item) {
        Vue.set(this.popupData, 'id', item.id);
        Vue.set(this.popupData, 'fieldType', item.fieldType);
        Vue.set(this.popupData, 'fieldZhName', item.fieldZhName);
        Vue.set(this.popupData, 'fieldEnName', item.fieldEnName);
        Vue.set(this.popupData, 'selectedField', item.id);
        Vue.set(this.popupData, 'selFun', item.function);
      }

      this.dialogTitle = 'X轴';
      this.dialogMsg = '';
      this.dialogVisible = true;
    },
    onUnSelectXColumn(selItem) {
      this.selectedFields = this.selectedFields.filter(m => m.id != selItem.id);
      this.xColumns = this.xColumns.filter(m => m.id != selItem.id);
      if (this.xColumns.length == 0) {
        this.yColumn = undefined;
      }
      this.refreshChart();

      this.allFields
        .filter(m => m.id == selItem.id)
        .forEach(item => {
          item.class = 'item';
        });
    },
    onSelectXField() {
      this.dialogMsg = '';

      let item = undefined;
      if (this.popupData.selectedField) {
        let items = this.allFields.filter(
          m => m.id == this.popupData.selectedField
        );
        item = items[0];
      }

      if (item) {
        Vue.set(this.popupData, 'fieldType', item.fieldType);
        Vue.set(this.popupData, 'fieldZhName', item.fieldZhName);
        Vue.set(this.popupData, 'fieldEnName', item.fieldEnName);
        let selFun = 'count';
        if (item.fieldType && item.fieldType == 'Date') {
          selFun = '日';
        }
        Vue.set(this.popupData, 'selFun', selFun);
      } else {
        Vue.set(this.popupData, 'fieldType', '');
        Vue.set(this.popupData, 'fieldZhName', '');
        Vue.set(this.popupData, 'fieldEnName', '');
        Vue.set(this.popupData, 'selFun', '');
      }
    },
    onSelectYField() {
      this.dialogMsg = '';

      let item = undefined;
      if (this.popupData.selectedField) {
        let items = this.allFields.filter(
          m => m.id == this.popupData.selectedField
        );
        item = items[0];
      }

      if (item) {
        Vue.set(this.popupData, 'fieldType', item.fieldType);
        Vue.set(this.popupData, 'fieldZhName', item.fieldZhName);
        Vue.set(this.popupData, 'fieldEnName', item.fieldEnName);
        let selUnit = '';
        if (item.fieldType && item.fieldType == 'Date') {
          selUnit = '日';
        }
        Vue.set(this.popupData, 'selUnit', selUnit);
        Vue.set(this.popupData, 'interval', '');
      } else {
        Vue.set(this.popupData, 'fieldType', '');
        Vue.set(this.popupData, 'fieldZhName', '');
        Vue.set(this.popupData, 'fieldEnName', '');
        Vue.set(this.popupData, 'selUnit', '');
        Vue.set(this.popupData, 'interval', '');
      }
    },
    onSelectYColumn() {
      this.popupData.id = 0;
      Vue.set(this.popupData, 'columnType', 'y');
      Vue.set(this.popupData, 'fieldType', '');
      Vue.set(this.popupData, 'selectedField', '');
      Vue.set(this.popupData, 'selUnit', '');
      Vue.set(this.popupData, 'interval', '');

      if (this.yColumn) {
        Vue.set(this.popupData, 'id', this.yColumn.id);
        Vue.set(this.popupData, 'fieldType', this.yColumn.fieldType);
        Vue.set(this.popupData, 'fieldZhName', this.yColumn.fieldZhName);
        Vue.set(this.popupData, 'fieldEnName', this.yColumn.fieldEnName);
        Vue.set(this.popupData, 'selectedField', this.yColumn.id);
        Vue.set(this.popupData, 'selUnit', this.yColumn.unit);
        Vue.set(this.popupData, 'interval', this.yColumn.interval);
      }

      this.dialogTitle = 'Y轴';
      this.dialogMsg = '';
      this.dialogVisible = true;
    },
    _saveXColumn() {
      if (this.popupData.columnType == 'x') {
        if (this.popupData.selectedField) {
          if (this.popupData.selectedField != this.popupData.id) {
            if (this.popupData.id > 0) {
              this.xColumns = this.xColumns.filter(
                m => m.id != this.popupData.id
              );
            }

            let columns = this.allFields.filter(
              m => m.id == this.popupData.selectedField
            );
            if (columns.length > 0) {
              this.xColumns.push({
                id: columns[0].id,
                column: columns[0].fieldEnName,
                fieldZhName: columns[0].fieldZhName,
                fieldEnName: columns[0].fieldEnName,
                fieldType: columns[0].fieldType,
                function: this.popupData.selFun,
              });

              if (!this.yColumn) {
                this.yColumn = { id: '' };
              }
            }
          } else {
            var columns = this.xColumns.filter(m => m.id == this.popupData.id);
            if (columns && columns.length > 0) {
              columns[0].function = this.popupData.selFun;
            }
          }

          this.refreshChart();
          this.dialogVisible = false;
        } else {
          this.dialogMsg = '请选择字段';
        }
      }
    },
    _saveYColumn() {
      if (this.popupData.columnType == 'y') {
        if (this.popupData.selectedField) {
          let columns = this.allFields.filter(
              m => m.id == this.popupData.selectedField
            ),
            column = columns[0];
          if (column.fieldType == 'Num' && this.popupData.interval == '') {
            this.dialogMsg = '请输入间隔';
            return;
          } else {
            this.yColumn = {
              id: columns[0].id,
              column: columns[0].fieldEnName,
              fieldZhName: columns[0].fieldZhName,
              fieldEnName: columns[0].fieldEnName,
              fieldType: columns[0].fieldType,
              unit: this.popupData.selUnit,
              interval: this.popupData.interval,
            };
          }
        } else {
          this.yColumn = { id: '' };
        }

        this.refreshChart();
        this.dialogVisible = false;
      }
    },
    onSave() {
      if (this.popupData.columnType == 'x') {
        this._saveXColumn();
      } else {
        this._saveYColumn();
      }
      console.log(this.popupData);
    },
    refreshChart() {
      console.log(this.xColumns);
      console.log(this.yColumn);

      this.myChart = this.$echarts.init(document.getElementById('dsChart'));
      this.myChart.setOption(ChartData.GetChartData(this.xColumns));
      this.myChart.on('click', params => {
        this.popupData.id = 0;
        var columns = this.xColumns.filter(m => m.id == params.value);
        if (columns.length > 0) {
          this.onSelectXColumn(columns[0]);
        }
        this.dialogVisible = true;
      });
    },
    filterChange() {
      if (this.queryFieldInput && this.queryFieldInput.length > 0) {
        var filter = this.allFields.filter(
          x =>
            (x.fieldEnName
              ? x.fieldEnName.indexOf(this.queryFieldInput) > -1
              : true) ||
            (x.fieldZhName
              ? x.fieldZhName.indexOf(this.queryFieldInput) > -1
              : true)
        );
      }
      this.allFields.forEach(item => {
        if (filter) {
          var e = filter.filter(m => m.id == item.id);
          if (e && e.length > 0) {
            item.class = item.class.replace(' hide', '');
          } else {
            item.class = item.class.replace(' hide', '');
            item.class = item.class + ' hide';
          }
        } else {
          item.class = item.class.replace(' hide', '');
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import './chart.scss';
</style>
